package cn.uway.controller.demo;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.uway.cache.LocalCache;
import cn.uway.pojo.demo.UserInfo;
import cn.uway.utils.SpringSecurityUtils;


@Controller
public class PageController {  
	
	@Autowired
	private  LocalCache  ehCache;  //注入ehCache
	
	
	@RequestMapping(value = "/" )
    public String  login(HttpServletRequest request, HttpServletResponse response ) {
    	
        return "login";
    }
	
	@RequestMapping(value = "/login" , method=RequestMethod.GET )
    public String  toLogin(HttpServletRequest request, HttpServletResponse response ) {    	
		
    	
        return "login";
    }
	
	
	
    @RequestMapping(value ="/welcome" /*, method=RequestMethod.POST */)
    public String  welcome(HttpServletRequest request, HttpServletResponse response ) {
    	
    	request.setAttribute("name", request.getParameter("name"));
    	
    	//测试从redis中获取session数据
    	
    	UserInfo userInfo = (UserInfo) request.getSession().getAttribute("USER_INFO");
    	System.out.println("=====================http session.getAttribute(USER_INFO)="+userInfo);
    	if(userInfo!=null){
    		System.out.println("=====================http session.getAttribute(USER_INFO).getUserName()="+userInfo.getLoginName());
    	}   
    	UserInfo shiroUserInfo = SpringSecurityUtils.getCurrentUser();
    	System.out.println("=====================shiro subject.getSession().getAttribute(USER_INFO)="+userInfo);
    	if(shiroUserInfo!=null){
    		System.out.println("===================== shiro subject.getSession().getAttribute(USER_INFO).getUserName()="+userInfo.getLoginName());
    	}     	
    	
    	//测试从ehcache缓存中获取数据
    	UserInfo  cachedUserInfo = (UserInfo)ehCache.getObject("test.Key");
    	System.out.println("=====================ehCache.getObject(test.key)="+cachedUserInfo);
    	if(cachedUserInfo!=null){
    		System.out.println("=====================ehCache.getObject(test.key).getUserName()="+cachedUserInfo.getLoginName());
    	}  
    	
        return "welcome";
    }
    
    @RequestMapping("/logout")
	public String logout(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		try {
			SecurityUtils.getSubject().getSession().stop();
		} catch (Exception e) {
		}
		
		return "redirect:/";
	}
    
}
